//
// Created by 高曦祥 on 2023/11/26.
//

#ifndef TINY_DB_SPIN_LOCK_H
#define TINY_DB_SPIN_LOCK_H

#include <atomic>
#include "util/base_types.h"

namespace TinyDB {

class SpinLock {
 public:
  SpinLock() {};
  ~SpinLock() = default;

  t_void Lock() {
    while (flag_.test_and_set(std::memory_order_acquire));
  }
  t_void UnLock() {
    flag_.clear(std::memory_order_release);
  }

 private:
  std::atomic_flag flag_ = ATOMIC_FLAG_INIT;
};

class SpinLockGuard {
 public:
  SpinLockGuard(SpinLock& lock) : lock_(lock) {
    lock_.Lock();
  }
  ~SpinLockGuard() {
    lock_.UnLock();
  }
 private:
  SpinLock& lock_;
};

}

#endif //TINY_DB_SPIN_LOCK_H
